using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.HtmlControls;
using Decav.Gatsb.Application;

namespace Decav.Gatsb.Web.Controls
{
    /// <summary>
    /// A link that goes to a <see cref="Location"/>'s page.
    /// </summary>
    public class GatsbLocationLink : HtmlAnchor
    {
        public GatsbLocationLink()
        {
        }

        private Location _location;

        /// <summary>
        /// Gets or sets the location.
        /// </summary>
        public Location Location
        {
            get
            {
                if (_location == null && LocationId != Guid.Empty)
                    _location = GatsbApplication.Current.GetLocation(LocationId);

                return _location;
            }
            set
            {
                Guid id = Guid.Empty;
                if (value != null)
                    id = value.Id;

                ViewState["LocationId"] = id;
                _location = value;

                SetLink();
            }
        }

        /// <summary>
        /// Gets or sets the ID of the location.
        /// </summary>
        public Guid LocationId
        {
            get
            {
                if (ViewState["LocationId"] == null)
                    return Guid.Empty;

                return (Guid)ViewState["LocationId"];
            }
            set
            {
                ViewState["LocationId"] = value;
                if (value == Guid.Empty)
                    _location = null;
                else
                    _location = GatsbApplication.Current.GetLocation(LocationId);

                SetLink();
            }
        }

        private void SetLink()
        {
            if (LocationId == Guid.Empty)
            {
                this.Visible = false;
                return;
            }

            this.Visible = true;
            HRef = string.Format("Place.aspx?id={0}", LocationId);
            InnerText = Location.Name;
        }

        protected override void OnPreRender(EventArgs e)
        {
            SetLink();
            base.OnPreRender(e);
        }
    }
}
